<template>
  <div class="pager-wrapper">
      <div v-if="loading" v-loading="loading" class="pager-loading"></div>
      <div v-else style="min-height: 70px">
        <template v-if="pager.approval_type !== 'NoProcess'">
          <proposed-pager
          v-if="isZWReceipt"
          :pager="pager"
          :queryData="queryData"
          :pointData="pointData"
          ref="proposedPager"
        />
        <approve-pager
          v-else
          :pager="pager"
          :queryData="queryData"
          :pointData="pointData"
          ref="approvePager"
        />
        </template>
      </div>
      
      <el-row
        type="flex"
        justify="center"
      >
        <el-button
          v-if="isFormKeyContain('LZ')"
          type="primary"
          size="small"
          @click="handSaveProcess"
        >保存流转</el-button>
        <el-button
          v-if="isFormKeyContain('ZP')"
          type="primary"
          size="small"
          @click="showSelectUserDialog('指派')"
        >指派</el-button>
        <el-button
          v-if="isFormKeyContain('JQ')"
          type="primary"
          size="small"
          @click="showSelectUserDialog('加签')"
        >加签</el-button>
        <el-button
          v-if="isFormKeyContain('BH')"
          type="danger"
          size="small"
          @click="handReject"
        >驳回</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialogProcess"
        >流程监控</el-button>
      </el-row>
      <!-- <el-row
        v-else-if="queryData.rejectKey && queryData.rejectKey.startsWith('TSP') && !isFormKeyContain('circulation')"
        type="flex"
        justify="center"
      >
        <el-button
          type="primary"
          size="small"
          @click="handSaveProcess"
        >保存流转</el-button>
      </el-row>
      <el-row
        v-else-if="queryData.rejectKey && queryData.rejectKey.startsWith('TSP') && isFormKeyContain('circulation')"
        type="flex"
        justify="center"
      >
        <el-button
          v-if="!queryData.isHand"
          type="primary"
          size="small"
          @click="showSelectUserDialog('指派')"
        >指派</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialogProcess"
        >流程监控</el-button>
      </el-row>
      <el-row
        v-else-if="queryData.isHand"
        type="flex"
        justify="center"
      >
        <el-button
          type="primary"
          size="small"
          @click="showDialogProcess"
        >流程监控</el-button>
      </el-row>
      <el-row
        v-else
        type="flex"
        justify="center"
      >
        <el-button
          v-if="!queryData.isHand"
          type="primary"
          size="small"
          @click="handSaveProcess"
        >提交</el-button>
      </el-row> -->
      <!-- 流程监控 -->
      <process-monitor
        ref="process"
        :fromTask="true"
        :showPager="false"
        :activities="activities"
        :processStatics="processStatics"
      ></process-monitor>
      <!-- 委托人 -->
      <el-dialog
        :title="dialogUserTitle"
        :visible.sync="dialogSelectUser"
        width="80%"
        style="margin-top: -6vh;"
      >
        <div
          class="radio-list"
          v-if="isFormKeyContain('') && modalType !== '加签'"
        >
          <el-radio-group v-model="handRadio">
            <el-radio
              v-for="(item, index) in pointNameList"
              :label="item.value"
              :key="index"
            >{{ item.name}}</el-radio>
          </el-radio-group>
        </div>
        <user-manager
          v-if="(handRadio && handRadio.indexOf('END') == -1) || modalType === '加签'"
          ref="userManager"
          :userOuter="hiddenOuter"
          :onSelectUsers="handSelectConsignor"
        ></user-manager>
        <!-- 结束确认框 -->
        <div v-else class="end_confirm">
          <div class="content">
            <i class="el-icon-warning" style="color: #e6a23c"></i>
            <span>确定要结束此流程吗？</span>
          </div>
          <div class="option">
            <el-button size="small" @click="dialogSelectUser = false">取消</el-button>
            <el-button type="primary" size="small" @click="handSaveProcess('end_process')">确定</el-button>
          </div>
        </div>
      </el-dialog>
  </div>
</template>
  
  <script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { mapGetters } from "vuex";
import { getUserLabel, getUserDepartment } from "@/api/user.js";
import { updateTaskPart, getTaskPubWord } from "@/api/work.js";
import {
  getPaperClassify,
  createDocument,
  getPagerById
} from "@/api/document.js";
import {
  getProcess,
  getProcessPointNames,
  startProcess,
  completeTasks,
  getCommentmap,
  getProcessMinitorGraph,
  postEntrustToOther,
  postCountersign,
  getCommentPro,
  getTaskProcessInfo1,
  getTaskInfoByUserIdAndTaskId
} from "@/api/workflow.js";
import { parseTime, filterObj } from "@/utils/index";

export default {
  name: "HandlePager",
  components: {
    Treeselect,
    "user-manager": () =>
      import("@/views/markSys/taskCenter/components/userManager.vue"),
    "process-monitor": () => import("../components/ProcessMinitor/index.vue"),
    ApprovePager: () => import('@/views/markSys/taskCenter/components/ApprovePager'),
    ProposedPager: () => import('@/views/markSys/taskCenter/components/ProposedPager'),
  },
  props: {
    pager: {
      type: Object
    },
    isReportTask: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    pager: {
      handler(data) {
        this.loading = false
      }

    },
    handRadio(data) {
      if (data) {
        // 选择节点对应对象
        const selectPoint = this.pointNameList.filter(e => e.value === data)[0];
        this.handRadioName = selectPoint.name;
      }
    }
  },
  data() {
    return {
      // pager: {},
      dialogSelectUser: false,
      isFirstAssign: false, // 是否第一次指派
      consignor: "", // 委托用户
      handRadio: "",
      handRadioName: "",
      activities: [],
      pubWordOptions: [], // 发文字号类型数组
      processStatics: {
        curCount: 0,
        doneCount: 0,
        willCount: 0
      }, // 流程监控节点统计
      loading: true,
      dialogProcessVisible: false,
      modalType: null,
      lineNum: 1,
      queryData: null,
      dialogUserTitle: "选择人员", // 人员选择对话框标题
      pointNameList: [], // 流程节点名称
      pointData: [],
    };
  },
  computed: {
    isFirstHandler() {
      const { issued_number = "", issued_date = "" } = this.pager;
      return (
        !this.queryData.isHand &&
        this.queryData.startUserId == this.id &&
        !issued_number &&
        !issued_date
      );
    },
    isCirculation() {
      const { issued_number = "", issued_date = "" } = this.pager;
      return (
        this.isFormKeyContain('circulation') &&
        !issued_number &&
        !issued_date
      );
    },
    ...mapGetters(["id", "name"]),
    hiddenOuter() {
      if (this.handRadioName === "领导审批") {
        return false;
      }
      return true;
    },
    // 根据processDesc 判断是否属于州委收文
    isZWReceipt() {
      const { approval_type } = this.pager
      return approval_type == 'Receipt'
    }
  },
  created() {
    this.queryData = this.$route.params;
    
    // 初始化发文字段信息内容
    this.requestPubwordType();
    this.requestProcessPointNames();
    this.requestCommenthi();
    this.requestProcessGraph();
  },
  methods: {
    parseTime,
    // 显示选择委托人对话框
    showSelectUserDialog(type, line = 1) {
      const modalTypeTitle = {
        加签: "加签",
        指派: "转下一步",
        委托: "选择委托人员"
      };
      if (type === "指派" && this.pager.approval_type !== 'NoProcess') {
        if(!this.isZWReceipt) {
          const documentInfo = this.$refs.approvePager.document
          const { pubPagerWord, pubPagerDate } = documentInfo;
          if (this.isFormKeyContain('circulation')) {
            if (!pubPagerWord) {
              this.$message.warning("请填写发文字号");
              return;
            }
            if (!pubPagerDate) {
              this.$message.warning("请填写发文日期");
              return;
            }
          }
        } else {
          const { headerData } = this.$refs.proposedPager
          const isEmpty = Object.keys(headerData).every(key => !headerData[key])
          if(isEmpty) {
            this.$message.warning("请完善拟办单基本信息");
            return;
          }
        }
      }
      this.dialogUserTitle = modalTypeTitle[type];
      this.dialogSelectUser = true;
      this.modalType = type;
      this.lineNum = line;
    },
    // 判断formKey是否包含指定值
    isFormKeyContain(value) {
      const { formKey } = this.queryData
      if(formKey) {
        return formKey.indexOf(value) > -1
      } else if(formKey == '') {
        return true
      }
      return false
    },
    // 处理委托
    handSelectConsignor(users) {
      if (!users.length) {
        this.$message.warning("请选择处理人");
        return;
      }
      // 委托
      if (this.modalType === "委托") {
        postEntrustToOther(this.queryData.targetId, users[0].id).then(res => {
          if (res && res.data.message === "转发任务成功") {
            this.$notify({
              title: "成功",
              message: "转发任务成功",
              type: "success",
              duration: 2000
            });
            this.$router.push({ name: "Index" });
          } else {
            this.$message.error("无效操作，转发任务失败");
          }
          this.$refs["userManager"].clearSelect();
          this.dialogSelectUser = false;
        });
      } else if (this.modalType === "加签") {
        const { id, nodeName } = this.queryData;
        const userIds = users.map(e => e.id.toString());
        postCountersign(id, nodeName, { adduserList: userIds }).then(res => {
          if (res && res.data.code == "200") {
            this.$notify({
              title: "成功",
              message: "加签成功",
              type: "success",
              duration: 2000
            });
          } else {
            this.$message.error("无效操作，加签失败");
          }
          this.$refs["userManager"].clearSelect();
          this.dialogSelectUser = false;
        });
      } else {
        // 指派
        this.handAssign(users);
      }
    },
    // 处理指派
    handAssign(users) {
      // 判断节点
      if (!this.handRadio) {
        this.$message.warning("请选择下一步节点");
        return;
      }
      const formatUsers = users.map(e => e.id.toString());
      const assignName = users.map(e => e.name);
      let _comment = ''
      let _pagerWord = ''
      let _pagerDate = ''
      let pagerParam = {}
      if (this.pager.approval_type !== 'NoProcess') {
        if(this.isZWReceipt) {
          const { headerData, comment } = this.$refs.proposedPager
          const { reciptNum, reciptDate } = headerData;
          pagerParam.fromData = headerData
          _comment = comment
          _pagerWord = reciptNum
          _pagerDate = reciptDate
        } else {
          const { document, comment } = this.$refs.approvePager
          const { pubPagerWord, pubPagerDate } = document;
          _comment = comment
          _pagerWord = pubPagerWord
          _pagerDate = pubPagerDate
        }
      }

      const paramObj = {
        pubPagerWord: _pagerWord,
        pubPagerDate: _pagerDate,
        dealReason: _comment || "已流转至" + assignName.join(","),
        dealType: "0",
        dealUserId: this.id,
        dealUserName: this.name,
        dealUnitId: "0",
        businessKey: this.queryData.targetId,
        line: this.handRadio,
        circulationUserStr: assignName,
        isZP: true,
        userList: formatUsers
      };
      completeTasks(this.queryData.id, {...paramObj, ...pagerParam}).then(res => {
        if (res && res.data.message === "完成任务成功") {
          this.$notify({
            title: "成功",
            message: "指派任务操作成功",
            type: "success",
            duration: 2000
          });
          const param = {
            user: formatUsers
          };
          const { issued_number, issued_date } = this.pager;
          if (this.pager.approval_type !== 'NoProcess' && !issued_number && !issued_date) {
            Object.assign(param, {
              issued_number: _pagerWord,
              issued_date: _pagerDate
            });
          }
          if (this.handRadioName === "任务分发") {
            Object.assign(param, { issued_superior: -1 });
          }
          updateTaskPart(this.queryData.targetId, param);
          this.$router.push({ name: "Index" });
        } else {
          this.$notify({
            title: "失败",
            message: "指派任务操作失败",
            type: "error",
            duration: 2000
          });
        }
      });
    },
    // 保存流程
    handSaveProcess(type) {
      let _comment = ''
      let _pagerWord = ''
      let _pagerDate = ''
      let pagerParam = {}
      if (this.pager.approval_type !== 'NoProcess') {
        if(this.isZWReceipt) {
          const { headerData, comment } = this.$refs.proposedPager
          const { reciptNum, reciptDate } = headerData;
          pagerParam.fromData = headerData
          _comment = comment
          _pagerWord = reciptNum
          _pagerDate = reciptDate
        } else {
          const { document, comment } = this.$refs.approvePager
          const { pubPagerWord, pubPagerDate } = document;
          _comment = comment
          _pagerWord = pubPagerWord
          _pagerDate = pubPagerDate
        }
      }
      
      let paramObj = {
        dealReason: _comment || " ",
        pubPagerWord: _pagerWord,
        pubPagerDate: _pagerDate,
        dealType: "0",
        dealUserId: this.id,
        dealUserName: this.name,
        dealUnitId: "0",
        isZP: false,
        businessKey: this.queryData.targetId
      };
      // 如果结束流程
      if(type === 'end_process') {
        paramObj.line =  this.handRadio
        paramObj.userList =  []
      }
      completeTasks(this.queryData.id, {...paramObj, ...pagerParam}).then(res => {
        if (res && res.data.message === "完成任务成功") {
          this.$notify({
            title: "成功",
            message: "保存流转成功",
            type: "success",
            duration: 2000
          });
          const param = {
            is_edit: "False"
          };
          const { issued_number, issued_date } = this.pager;
          if (this.pager.approval_type !== 'NoProcess' && !issued_number && !issued_date) {
            Object.assign(param, {
              issued_number: _pagerWord,
              issued_date: _pagerDate
            });
          }
          // if(this.isFirstAssign || this.isFirstHandler){
          //     Object.assign(param,{'issued_number': pubPagerWord, 'issued_date': pubPagerDate})
          //   }
          updateTaskPart(this.queryData.targetId, param);
          this.$router.push({ name: "Index" });
        } else {
          this.$notify({
            title: "失败",
            message: "保存流转失败",
            type: "error",
            duration: 2000
          });
        }
      });
    },
    // 驳回
    handReject() {
      let _comment = ''
      if(this.isZWReceipt) {
        const { comment } = this.$refs.proposedPager
        _comment = comment
      } else {
        const { comment } = this.$refs.approvePager
        _comment = comment
      }
      if (!_comment) {
        this.$message.warning("请填写审批意见");
        return;
      }
      const param = {
        dealReason: _comment,
        dealType: "1",
        dealUserId: this.id,
        dealUserName: this.name,
        dealUnitId: "",
        rejectElemKey: this.queryData.rejectKey
      };
      completeTasks(this.queryData.id, param).then(res => {
        if (res && res.data) {
          this.$notify({
            title: "成功",
            message: "驳回审批成功",
            type: "success",
            duration: 2000
          });
          this.$router.push({ name: "Index" });
        } else {
          this.$notify({
            title: "失败",
            message: "驳回审批失败",
            type: "error",
            duration: 2000
          });
        }
      });
    },
    // 委托
    handEntrust() {
      postEntrustToOther(this.queryData.targetId, "32").then(res => {
        if (res && res.data.message === "转发任务成功") {
          this.$notify({
            title: "成功",
            message: "转发任务成功",
            type: "success",
            duration: 2000
          });
          this.$router.push({ name: "Index" });
        }
      });
    },
    // 显示流程监控页面
    showDialogProcess() {
      this.requestProcessMinitor();
      this.$refs.process.dialogProcessVisible = true;
    },
    // 获取流程高亮图
    requestProcessGraph() {
      const { proInsId, proDefId } = this.queryData;
      if (proInsId && proDefId) {
        getProcessMinitorGraph({
          proDefid: proDefId,
          proInsid: proInsId
        }).then(res => {});
      }
    },
    // 获取发文字号列表
    requestPubwordType() {
      getTaskPubWord().then(res => {
        this.pubWordOptions = res.data.results;
      });
    },
    // 获取流程监控数据
    requestProcessMinitor() {
      // let result = []
      // Object.keys(this.pointData).forEach(
      //   key =>{
      //     let point = this.pointData[key]
      //     if(point.length){
      //       point.forEach(
      //         e =>{
      //           e.name = key
      //         }
      //       )
      //       result = result.concat(point)
      //     }
      //   }
      // )
      // this.activities = result
      getTaskProcessInfo1(this.pager.id).then(res => {
        const { curCount, doneCount, willCount, data, proDefKey } =
          (res.data && res.data.data) || {};
        this.activities = data;
        this.processStatics = {
          modelName: proDefKey,
          curCount: curCount,
          doneCount: doneCount,
          willCount: willCount
        };
      });
      // getProcessMinitor(this.queryData.proId).then(
      //   res => {
      //     const data = res.data
      //     data.forEach(
      //       e => {
      //         e._startTime = parseTime(e.startTime, '{y}-{m}-{d}')
      //         e._endTime = parseTime(e.endTime, '{y}-{m}-{d}')
      //       }
      //     )
      //   }
      // )
    },
    // 获取流程节点名称
    requestProcessPointNames() {
      const { id } = this.queryData;
      getProcessPointNames(id).then(res => {
        const list = res.data.data;
        let data = [];
        if (!list.length) return;
        list.forEach(e => {
          if (Object.keys(e).length) {
            data.push({ name: Object.values(e)[0], value: Object.keys(e)[0] });
          }
        });
        this.pointNameList = data;
        this.handRadio = data[0].value
      });
    },
    // 遍历所有用户
    getUsersList(data, result) {
      data.forEach(item => {
        // result = [...result, ...item.user_department]
        item.user_department.forEach(user => {
          result.push(user);
        });
        if (item.child && item.child.length > 0) {
          this.getUsersList(item.child, result);
        }
      });
      return result;
    },
    // 获取审批记录
    requestCommenthi() {
      const { targetId, nodeName } = this.queryData;
      let _comment = ''
      if (targetId) {
        // getCommentPro(proInsId, proDefId).then(res => {
        //   this.pointData = res.data.data;
        // });
        getTaskInfoByUserIdAndTaskId({
          userId: this.id,
          bussKey: targetId
        }).then(res => {
          const { comment, fromData } = res.data.data
          if(!this.queryData.variables && fromData) {
            this.queryData.variables = { fromData: typeof fromData == 'stirng' ? JSON.parse(fromData) : fromData }
          }
          // 如果是拟办单处理 保存流转时填入默认值
          if(this.isZWReceipt && this.isFormKeyContain('LZ')) {
            _comment = 
              nodeName === '办结归档' 
                ? '归档' 
                : nodeName === '传阅'
                  ? '已阅'
                  : '已办' 
            this.$refs.proposedPager.comment = _comment
          }

          this.pointData = comment;
        });
      }
    }
  }
};
</script>
  <style media="printContent">
/* @page {
  size: auto;
  margin: 10mm 15mm 0;
} */
</style>

<style lang="scss">
.pager-wrapper {
  margin: 0 20px 20px;
  overflow-x: hidden;
  .pager-loading {
    height: calc(100vh - 230px);
  }
}
  
  .radio-list {
    padding: 0 20px 12px;
    text-align: center;
    .el-radio {
      margin-right: 15px;
      .el-radio__inner {
        display: none;
      }
      .el-radio__label {
        font-size: 16px;
        color: #b5b5b5;
        border: 1px solid;
        padding: 5px 10px;
        border-radius: 13px;
      }
      .el-radio__input.is-checked + .el-radio__label {
        color: #fff;
        background: #409eff;
      }
    }
  }
  .end_confirm {
    width: 308px;
    margin: 78px auto 10px;
    padding: 16px 20px;
    vertical-align: middle;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    font-size: 16px;
    box-shadow: 0 2px 12px 0 #e0e0e0;
    .content {
      margin-bottom: 20px;
    }
    .option { 
      text-align: right;
    }
  }
  .input-warpper {
    max-width: 800px;
    width: 100%;
    margin: 10px auto;

    .name {
      width: 80px;
      color: #797979;
      line-height: 30px;
    }
  }

  .el-divider--horizontal {
    margin: 24px auto;
  }
  .el-button + .el-button {
    margin-left: 10px;
  }
  .el-dialog__body {
    padding: 20px;
  }
</style>
  